<template>
  <div class="upimg">
    <el-upload
      :class="{disable:dialogImageUrl}"
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="FileList"
      :http-request="uploadImg"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-input v-model="imgUrl" placeholder="强制设置图片跳过上传" />
  </div>
</template>

<script>
// 实例化cos服务
import COS from 'cos-js-sdk-v5'
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDnRccNs754oMgYR3PUJrCKDqDNp10kFXb',
  SecretKey: 'qWx84jbFfphJeu0tWu1EBsPM9l9H8i4A'
})
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      imgUrl: '',
      sss: 0,
      percentage: 0
    }
  },
  computed: {
    FileList() {
      if (this.dialogImageUrl) {
        if (this.sss === 0) {
          return [{ url: this.dialogImageUrl, status: 'none' }]
        } else {
          return [{ url: this.dialogImageUrl, status: 'success' }]
        }
      } else {
        return []
      }
    }
  },
  methods: {
    uploadImg(file) {
      console.log(file)
      this.dialogImageUrl = file.file // 让上传按钮立即消失
      cos.uploadFile({
        Bucket: 'hr-avatar-1314826525', /* 储存桶名字，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: Date.now().toString(), /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file.file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          console.log(progressData)
          this.percentage = progressData.percent * 100
          if (this.percentage === 100 && progressData.percent === 1) {
            this.sss = 1
          }
        }
      },
      // 改为箭头函数否则this指向不对（普通函数this指向：谁调用指向谁，箭头函数：指向整个vue实例）
      (err, data) => {
        if (err) {
          console.log('上传失败', err)
          this.dialogImageUrl = ''
        } else {
          console.log('上传成功', data)
          this.dialogImageUrl = 'http://' + data.Location
        }
      })
    },
    handleRemove() {
      this.dialogImageUrl = ''
      this.sss = 0
      this.percentage = 0
    },
    handlePictureCardPreview() {
      this.dialogVisible = true
    }
  }
}
</script>

<style lang='scss' scoped>
.upimg{
  .disable{
     ::v-deep .el-upload--picture-card{
        display: none;
    }
  }
}
</style>
